<template>
  <div>
    <el-card>
      <CategorySelector @changeCategoryId="changeCategoryId" :isShowList="isShowList"></CategorySelector>
    </el-card>
    <el-card style="margin-top: 20px">
      <div v-show="isShowList">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!category3Id"
          @click="addAttr"
          >添加属性</el-button
        >
        <el-table :data="attrList" style="width: 100%" border>
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="150">
          </el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                type="success"
                v-for="attrVal in row.attrValueList"
                :key="attrVal.id"
                >{{ attrVal.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150">
            <template slot-scope="{ row, $index }">
              <HintButton
                title="修改"
                icon="el-icon-edit"
                type="warning"
                size="mini"
                @click="updateAttrValue(row)"
              ></HintButton>
                <el-popconfirm
                  :title="`您确定删除${row.attrName}吗`" @onConfirm="deleteAttr(row)"
                >
                  <HintButton
                    title="删除"
                    icon="el-icon-delete"
                    type="danger"
                    size="mini"
                    slot="reference"
                  >
                  </HintButton>
                </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="!isShowList">
        <el-form
          :inline="true"
          ref="attrForm"
          :rules="attrRules"
          :model="attrForm"
        >
          <el-form-item label="属性名" prop="attrName">
            <el-input
              v-model="attrForm.attrName"
              placeholder="请输入属性名"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" @click="addAttrValue" :disabled="!attrForm.attrName"
          >添加属性值</el-button
        >
        <el-button @click="cancelAddOrUpdate">取消</el-button>
        <el-table
          :data="attrForm.attrValueList"
          style="width: 100%; margin-top: 20px; margin-bottom: 20px"
          border
        >
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称" width="width">
            <template slot-scope="{ row, $index }">
              <el-input
                :ref="$index"
                size="mini"
                v-show="row.isEdit"
                v-model="row.valueName"
                @blur="showSpan(row)"
                @keyup.enter.native="showSpan(row)"
              ></el-input>
              <span
                style="display: block; width: 100%"
                v-show="!row.isEdit"
                @click="showInput(row, $index)"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <template>
                <el-popconfirm
                  :title="`您确定删除${row.valueName}吗`" @onConfirm="attrForm.attrValueList.splice($index, 1)"
                >
                  <HintButton
                    title="删除"
                    icon="el-icon-delete"
                    type="danger"
                    size="mini"
                    slot="reference"
                  >
                  </HintButton>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="saveAttr" :disabled="attrForm.attrValueList.length === 0">保存</el-button>
        <el-button @click="cancelAddOrUpdate">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";
export default {
  data() {
    return {
      category1Id: "",
      category2Id: "",
      category3Id: "",
      attrList: [],
      isShowList: true,
      attrForm: {
        attrName: "",
        attrValueList: [],
        categoryId: 0,
        categoryLevel: 3,
      },
      attrRules: {
        attrName: [
          { required: true, message: "请输入属性名", trigger: "blur" },
          {
            min: 2,
            max: 5,
            message: "长度在 2 到 5 个字符",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    async changeCategoryId({ categoryId, level }) {
      if (level === 1) {
        this.attrList = [];
        this.category2Id = "";
        this.category3Id = "";
        this.category1Id = categoryId;
      } else if (level === 2) {
        this.attrList = [];
        this.category3Id = "";
        this.category2Id = categoryId;
      } else if (level === 3) {
        this.category3Id = categoryId;
        this.attrForm.categoryId = categoryId;
        this.getAttrList();
      }
    },
    addAttr() {
      this.isShowList = false;
      this.attrForm = {
        attrName: "",
        attrValueList: [],
        categoryId: this.category3Id,
        categoryLevel: 3,
      };
    },
    addAttrValue() {
      this.attrForm.attrValueList.push({
        attrId: this.attrForm.id,
        valueName: "",
        isEdit: true,
      });
      this.$nextTick(()=>{
           this.$refs[this.attrForm.attrValueList.length - 1].focus();
      })
    },
    updateAttrValue(row) {
      this.isShowList = false;
      this.attrForm = cloneDeep(row);
      this.attrForm.attrValueList.forEach((item) => {
        this.$set(item, "isEdit", false);
      });
    },
    cancelAddOrUpdate() {
      this.isShowList = true;
      this.attrForm = {
        attrName: "",
        attrValueList: [],
        categoryId: this.category3Id,
        categoryLevel: 3,
        id: 0,
      };
    },
    saveAttr() {
      this.$refs.attrForm.validate(async (valid) => {
        if (valid) {
           this.attrForm.attrValueList = this.attrForm.attrValueList.filter(item => {
            if(item.valueName !== '') {
              delete item.isEdit
              return true
            }
          })
          if(this.attrForm.attrValueList.length === 0) {
            return this.$message.error('您必须添加属性值')
          }
          try {
            let result = await this.$API.attr.saveAttrInfo(this.attrForm);
            this.$message.success("添加属性成功");
            this.isShowList = true;
            this.getAttrList();
          } catch (e) {
            this.$message.error("添加属性失败");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async deleteAttr(row) {
      try {
        let result = await this.$API.attr.deleteAttr(row.id)
        if(result.code === 200 || result.code === 20000) {
          this.$message.success('删除属性成功')
          this.getAttrList()
        }
      }catch(e) {
        this.$message.error('删除属性失败')
      }
    },  
    async getAttrList() {
      try {
        let result = await this.$API.attr.getAttrInfoList(
          this.category1Id,
          this.category2Id,
          this.category3Id
        );
        this.attrList = result.data;
      } catch (e) {
        this.$message.error("获取商品属性失败");
      }
    },
    showSpan(row) {
      let attr = this.attrForm.attrValueList;
      if (row.valueName.trim() === "") return;
      let isRepeat = attr.some((item) => {
        if (item !== row) {
          return item.valueName === row.valueName;
        }
      });
      if (isRepeat) return;
      row.isEdit = false;
    },
    showInput(row, index) {
      row.isEdit = true;
      //等input加载完毕 在获取焦点
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
  },
};
</script>

<style lang="scss">
</style>